package com.gang.music.core.aop;

import com.gang.music.core.annotation.Permission;
import com.gang.music.core.exception.NoPermissionException;
import com.gang.music.core.interfaces.PermissionCheck;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * AOP 权限自定义检查
 */
@Aspect
@Component
public class PermissionAop {
	
	@Autowired
	private PermissionCheck permissionCheck;
	
	@Pointcut(value = "@annotation(com.gang.music.core.annotation.Permission)")
	private void cutPermission() {

	}

	@Around("cutPermission()")
	public Object doPermission(ProceedingJoinPoint point) throws Throwable {
		MethodSignature ms = (MethodSignature) point.getSignature();
		Method method = ms.getMethod();
		Permission permission = method.getAnnotation(Permission.class);
		Object[] permissions = permission.value();
			boolean result = permissionCheck.checkPermission(permissions);
			if (result) {
				return point.proceed();
			} else {
				throw new NoPermissionException("您没有当前操作的权限");
			}
		}
}
